<template>
  <div class="wrap">
    <div class="header">
      <div class="left">
        <div style="display: inline-block">
          <el-input size="small" style="width: 200px" v-model="queryParams.keyword" placeholder="搜索运营账号"></el-input>
          <el-button size="small" type="primary" @click="changeOption">{{ $t('common.search') }}</el-button>
        </div>
      </div>
      <div class="right">
        <el-button size="small" type="primary" @click="editAdmin()">添加运营</el-button>
      </div>
    </div>
    <div class="content">
      <el-table v-loading="loading" :data="data" border>
        <el-table-column prop="account" label="运营账号" align="center" min-width="120">
          <template v-slot="{ row }">
            <el-link :underline="false">{{ row.account }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="roleType" label="账号角色" align="center" min-width="100">
          <template v-slot="{ row }">
            {{ getRoleTypeName(row.roleType) }}
          </template>
        </el-table-column>
        <el-table-column prop="accountList" label="店铺" align="center" min-width="100">
          <template slot-scope="{ row }">
            <template v-if="row.accountList.length === 0">
              {{ $t('childList.Not authorized yet') }}
            </template>
            <template v-else-if="row.accountList.length === 1">
              {{ row.accountList[0].nickname }}
            </template>
            <template v-else>
              <el-tooltip class="item" effect="dark" placement="top-end">
                <div slot="content">
                  <div v-for="accountItem in row.accountList" :key="accountItem.accountId">{{ accountItem.accountType }}，{{ accountItem.nickname }}</div>
                </div>
                <div>{{ row.accountList.length }}</div>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="roles" label="功能权限" align="center" min-width="150">
          <template slot-scope="{ row }">
            <template v-if="row.roles.length === 0">-</template>
            <template v-else>
              {{ getRolesStr(row.roles) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="用户状态" align="center" min-width="100">
          <template slot-scope="{ row }">
            {{ row.status === 1 ? $t('childList.In cooperation') : $t('childList.Stop cooperation') }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('table.createTime3')" align="center" min-width="100"></el-table-column>
        <el-table-column prop="remark" :label="$t('table.备注')" align="center" width="300" show-overflow-tooltip></el-table-column>

        <el-table-column :label="$t('table.operate')" align="left" width="200">
          <template slot-scope="{ row }">
            <el-button type="primary" @click="editAdmin(row)">{{ $t('childList.Modify Operations') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-wrap">
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-sizes="[20]"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </div>

    <el-dialog :visible.sync="dialogEdit" width="1000px" :title="currentForm.id ? $t('childList.Modify Operations') : $t('childList.Add Operations')" class="admin-dialog">
      <el-form label-width="100px" :rules="rules" ref="userForm" :model="currentForm">
        <el-form-item label="账号名" prop="account">
          <el-input v-model="currentForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentForm.password">
            <template slot="append">
              <el-button @click="createPassword">{{ $t('childList.random') }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('table.备注')" prop="remark">
          <el-input v-model="currentForm.remark" type="textarea" maxlength="500" autosize placeholder="选填，保存更多账号细节"></el-input>
        </el-form-item>
        <el-form-item label="账号角色" prop="roleType">
          <template v-if="!currentForm.id">
            <el-radio-group v-model="currentForm.roleType" @change="changeRoleType">
              <el-radio v-for="item in roleTypeList" :key="item.key" :label="item.key">
                {{ item.name }}
                <el-tooltip class="item" effect="dark" placement="top">
                  <template #content>
                    <div>
                      {{item.label}}
                    </div>
                  </template>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            {{ getRoleTypeName(currentForm.roleType) }}
          </template>
        </el-form-item>

        <el-form-item label="功能权限" prop="roles" v-show="currentForm.roleType == 'commissioner'">
          <template>
            <el-form-item style="margin-bottom: 0">
              <el-checkbox-group v-model="currentForm.roles">
                <el-checkbox v-for="item in rolesList2" :label="item.key" :key="item.key" :disabled="item.key == 'dataStatistics'">
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </template>
        </el-form-item>

        <template>
          <el-form-item label="店铺权限" prop="accountAuth" v-show="currentForm.roleType == 'commissioner'">
            <template v-if="currentForm.handleModel === 'account'">
              <div class="font-red font-bold">
                {{ '同一业务权限中，1个店铺只能绑定在1个运营账号下，以下仅列出未被任何运营绑定的店铺' }}
              </div>
              <template v-if="allUserAccount.length > 0">
                <div class="font-grey f13">
                  {{ '如需将已绑定的店铺换绑到其他运营账号下，请取消勾选，点击「确认」后前往对应运营账号编辑页面继续操作' }}
                </div>
                <div class="account-auth-content" v-for="(item, index) in allUserAccount" :key="index">
                  <div class="user-account">{{ item.name }}</div>
                  <div class="account-list">
                    <el-checkbox class="account-checkbox" :value="isAllAccount(index)" @change="chooseAllAccount(index)">全选</el-checkbox>
                    <el-checkbox
                      class="account-checkbox"
                      v-for="account in item.child"
                      :label="account.ogAccountId"
                      :key="account.ogAccountId"
                      v-model="currentForm.accountAuth"
                      @change="testAccount"
                    >
                      <el-tooltip class="item" effect="dark" :content="account.showName" placement="top">
                        <span class="account-label">{{ truncate(account.showName, 10) }}</span>
                      </el-tooltip>
                    </el-checkbox>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="font-grey f13">
                  {{ $t('暂无可绑定的店铺，请前往其他运营账号下取消绑定后再返回操作') }}
                </div>
              </template>
            </template>
          </el-form-item>
        </template>

        <el-form-item :label="$t('table.status')" prop="status">
          <el-radio-group v-model="currentForm.status">
            <el-radio :label="1">{{ $t('childList.In cooperation') }}</el-radio>
            <el-radio :label="0">{{ $t('childList.Stop cooperation') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="submitForm()" :loading="dialogLoading">{{ $t('common.save') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deepCopy, generateRandomString } from '@/utils';
import request from '@/utils/request';
// import userAccountOptions from "@/views/order/mixin/userAccountOptions";
import { editAdmin, getAdminList, getAdminLoginWithKey, getAllAuthAccount, createUser, getUserList } from '@/api/user';
import { getWarehouseList } from '@/api/warehouse';
import user from '@/store/modules/user';
import {
  getRoleName,
  getRoleTypeName,
  ROLE_OPERATE,
  ROLE_FINANCE,
  ROLE_DATA_STATISTICS,
  ROLE_PACKAGE_MANAGEMENT,
  ROLE_INVENTORY_MANAGEMENT,
  ROLE_ACCOUNT_MANAGEMENT,
  ROLE_CARGO_MANAGEMENT,
  ROLE_WORKORDER_MANAGEMENT
} from '@/utils/user';
import { MessageBox } from 'element-ui';
import { getUserLoginWithKey } from '@/api/user';

const rolesKey = {
  dataStatistics: ROLE_DATA_STATISTICS, // 数据统计
  packageManagement: ROLE_PACKAGE_MANAGEMENT, // 小包管理
  inventoryManagement: ROLE_INVENTORY_MANAGEMENT, // 库存管理
  accountManagement: ROLE_ACCOUNT_MANAGEMENT ,// 账号管理
  cargoManagement: ROLE_CARGO_MANAGEMENT ,// 货件管理
  workOrderManagement: ROLE_WORKORDER_MANAGEMENT // 工单管理
};
export default {
  name: 'childList',
  // mixins: [userAccountOptions],
  computed: {
    rolesList1() {
      return this.roleList.filter((item) => item.type === 1 && item.isOperate);
    },
    rolesList2() {
      return this.roleList.filter((item) => item.type === 2 && item.isOperate);
    },
    rolesListFinance() {
      return this.roleList.filter((item) => item.isFinance);
    }
    // formAccountList() {
    //   let oneShippingIndex = this.currentForm.roles.indexOf(rolesKey.oneShipping);
    //   let middleTransferIndex = this.currentForm.roles.indexOf(rolesKey.middleTransfer);

    //   // let isOneShipping = false
    //   // if (this.currentForm.roles.includes('oneShipping')) {
    //   //   isOneShipping = true
    //   // }
    //   // console.log(this.allUserAccount)

    //   const arr = [];
    //   this.allUserAccount
    //     .filter((item) => item.effect)
    //     .map((item) => {
    //       const obj = deepCopy(item);
    //       obj.userAccountList = obj.userAccountList.filter((accountItem) => {
    //         if (oneShippingIndex !== -1) {
    //           return accountItem.oneShippingAdminId === 0 || accountItem.oneShippingAdminId === this.currentForm.id;
    //         } else if (middleTransferIndex !== -1) {
    //           return (
    //             (accountItem.middleTransferAdminId === 0 && accountItem.is_packet === false) ||
    //             (accountItem.middleTransferAdminId === this.currentForm.id && accountItem.is_packet === false)
    //           );
    //         }
    //         return false;
    //       });
    //       if (obj.userAccountList.length > 0) {
    //         arr.push(obj);
    //       }
    //     });
    //   return arr;
    // },
    // formUserList() {
    //   let oneShippingIndex = this.currentForm.roles.indexOf(rolesKey.oneShipping);
    //   let middleTransferIndex = this.currentForm.roles.indexOf(rolesKey.middleTransfer);
    //   if (oneShippingIndex === middleTransferIndex) {
    //     return [];
    //   }

    //   return this.allUserAccount.map((item) => {
    //     item.adminAccount = '';
    //     let currentAdminId = 0;
    //     if (oneShippingIndex !== -1) {
    //       item.adminAccount = item.oneShippingAdminAccount;
    //       currentAdminId = item.oneShippingAdminId;
    //     } else if (middleTransferIndex !== -1) {
    //       item.adminAccount = item.middleTransferAdminAccount;
    //       currentAdminId = item.middleTransferAdminId;
    //     }
    //     item.disable = this.currentForm.id !== 0 && this.currentForm.id === currentAdminId;
    //     return item;
    //   });
    // }
  },
  data() {
    // 校验用户名是否有重复的
    const checkAccount = (rule, value, callback) => {
      request({
        url: '/user/checkAccount',
        method: 'get',
        params: this.currentForm,
        handleError: true
      }).then((res) => {
        if (res.error !== 0) {
          callback(new Error(res.message));
        } else {
          callback();
        }
      });
    };

    const roleTypeList = [
      {
        name: this.$t('childList.主管'),
        label:this.$t('childList.主管内容'),
        key: ROLE_OPERATE // 唯一的key
      },
      {
        name: this.$t('childList.专员'),
        label:this.$t('childList.专员内容'),
        key: ROLE_FINANCE // 唯一的key
      }
    ]; // 账号角色

    const roleList = [
      {
        name: '数据统计',
        key: rolesKey.dataStatistics,
        type: 2,
        isFinance: true,
        isOperate: true
      }, // 财务数据
      {
        name: '小包管理',
        key: rolesKey.packageManagement,
        type: 2,
        isFinance: true,
        isOperate: true
      }, // 数据管理

      {
        name: '库存管理',
        key: rolesKey.inventoryManagement,
        type: 2,
        isFinance: true,
        isOperate: true
      }, // 用户管理

      {
        name: '账号管理',
        key: rolesKey.accountManagement,
        type: 2, // 用于区分业务权限还是数据权限 1：业务权限 2：数据权限
        isFinance: true,
        isOperate: true
      },
      {
        name: '货件管理',
        key: rolesKey.cargoManagement,
        type: 2, // 用于区分业务权限还是数据权限 1：业务权限 2：数据权限
        isFinance: true,
        isOperate: true
      },
      {
        name: '工单管理',
        key: rolesKey.workOrderManagement,
        type: 2, // 用于区分业务权限还是数据权限 1：业务权限 2：数据权限
        isFinance: true,
        isOperate: true
      }
    ]; // 权限功能
    // if(!this.$store.getters.showMenuRemittance){
    //   const index = roleList.findIndex(item=> item.key === rolesKey.remittanceManage)
    //   roleList.splice(index, 1)
    // }

    return {
      queryParams: {
        page: 1,
        pageSize: 20,
        keyword: ''
      },
      data: [],
      loading: false,
      total: 0,
      currentForm: {
        id: 0,
        account: '',
        name: '',
        password: '',
        userAuth: [],
        accountAuth: [],
        status: 1,
        allUser: false,
        remark: '', // 备注
        roleType: ROLE_OPERATE, // 角色类型
        warehouseId: '', // 仓库
        roles: [], // 权限
        handleModel: 'account' // 操作类型
      },
      defaultForm: null,
      isEdit: false, // 用于判断添加还是编辑
      dialogEdit: false,
      dialogLoading: false,
      rules: {
        account: [
          { required: true, message: this.$t('common.pleaseFillIn'), trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/, message: this.$t('user.userValid3'), trigger: 'blur' }
          // { validator: checkAccount, trigger: 'blur' }
        ],
        password: [{ required: true, message: this.$t('childList.userValid4'), trigger: ['blur', 'change'], min: 6 }],
        roleType: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }]
        // warehouseId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }]
      },
      warehouseList: [], // 获取所有仓库
      roleTypeList: roleTypeList,
      roleList: roleList,
      financeRoleList: [],
      rolesKey,
      allUserAccount: [],
      allOldUserAccount: [],
      currentRow: null,
      unAllUserAccount: []
    };
  },
  created() {
    this.defaultForm = deepCopy(this.currentForm);
    this.getData();
    // this.getWarehouse(); // 获取仓库
    // this.getAllAuthAccount();
  },
  methods: {
    getRoleTypeName,
    truncate(text, length) {
      if (text.length > length) {
        return text.substring(0, length) + '...';
      }
      return text;
    },
    jumpAdmin(row) {
      // getAdminLoginWithKey(row.id)
      //   .then(res=>{
      //     window.open(res.data.url,'_blank')
      //   })
    },
    getData() {
      this.loading = true;
      getUserList(this.queryParams).then((res) => {
        this.loading = false;
        this.data = deepCopy(res.data);
        this.total = res.info.total;
        this.allUserAccount = res.info.platformTypeList;
        this.unAllUserAccount = res.info.ubPlatformTypeList;
        this.allOldUserAccount = deepCopy(this.allUserAccount);
      });
    },
    // getAllAuthAccount() {
    //   this.authLoading = true;
    //   getAllAuthAccount().then((res) => {
    //     this.authLoading = false;
    //     this.allUserAccount = res.data;
    //   });
    // },
    // 编辑运营
    editAdmin(row = null) {
      // console.log(row)
      this.isEdit = !!row;
      this.dialogEdit = true;
      this.currentRow = null;
      if (row) {
        this.currentRow = deepCopy(row);
        // this.currentForm = deepCopy(row)
        this.currentForm.id = row.id;
        this.currentForm.account = row.account;
        this.currentForm.name = row.name;
        this.currentForm.password = row.password;
        this.currentForm.status = row.status;
        // this.currentForm.userAuth = [];
        this.currentForm.accountAuth = row.accountAuth;

        this.currentForm.allUser = false;
        if (row.authType === 1) {
          // 是否全权限
          this.currentForm.allUser = true;
        }
        this.currentForm.roleType = row.roleType;
        this.currentForm.roles = row.roles;
        this.currentForm.handleModel = 'account';
        this.currentForm.remark = row.remark;
        //合并
        this.allUserAccount = deepCopy(this.allOldUserAccount);
        if (this.currentForm.roleType == 'commissioner') {
          row.accountList.forEach((userItem) => {
            this.allUserAccount.forEach((item,i) => {
              //没有平台店铺直接删除不显示
              if(item.child.length==0){
                 this.allUserAccount.splice(i,1)
              }
              //显示用户已绑的店铺和没有绑定的店铺
              item.child.forEach((citem, index) => {
                if (citem.child_id!=0&&citem.child_id != userItem.child_id) {

                  item.child.splice(index, 1);
                }

              });
            });
          });
          console.log(this.allUserAccount)
        }
      } else {
        this.currentForm = deepCopy(this.defaultForm);
        //打散
        this.allUserAccount = [];
        this.allUserAccount = deepCopy(this.unAllUserAccount);
        this.currentForm.roles.push(rolesKey.dataStatistics);
      }
    },

    // 保存
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 专员
          if (this.currentForm.roleType === 'commissioner') {
            if (this.currentForm.roles.length === 0) {
              this.$errorMessage('请至少选择一个权限');
              return;
            }
          }
          if (this.currentForm.roleType == '') {
            this.$errorMessage('请至少选择一个角色权限');
            return;
          }
          const postData = deepCopy(this.currentForm);
          this.dialogLoading = true;
          if (postData.id) {
            createUser(postData).then((res) => {
              this.dialogLoading = false;
              if (res.error === 0) {
                this.dialogEdit = false;
                this.$successMessage(res.message);
                this.getData();
                // this.$store.dispatch('user/getInfo');
              } else {
                this.$errorMessage(res.message);
              }
            });
          } else {
            console.log(postData);
            createUser(postData).then((res) => {
              this.dialogLoading = false;
              if (res.error === 0) {
                this.dialogEdit = false;
                this.$successMessage(res.message);
                this.getData();
                // this.$store.dispatch('user/getInfo');
              } else {
                this.$errorMessage(res.message);
              }
            });
          }
        }
      });
    },
    // 店铺权限
    checkGroup() {
      if (this.currentForm.userAuth.indexOf('*') !== -1) {
        this.currentForm.userAuth = ['*'];
      }
    },
    // 搜索
    changeOption() {
      this.queryParams.page = 1;
      this.getData();
    },
    chooseAccount() {},
    getWarehouse() {
      getWarehouseList({
        page: 1,
        pageSize: 100
      }).then((res) => {
        this.warehouseList = res.data;
        if (this.warehouseList.length === 1) {
          this.currentForm.warehouseId = this.warehouseList[0].id;
        }
      });
    },
    // 一件代发和中转送仓只能选一个
    checkRoles() {
      const key1 = rolesKey.oneShipping;
      const key2 = rolesKey.middleTransfer;
      const index1 = this.currentForm.roles.indexOf(key1);
      const index2 = this.currentForm.roles.indexOf(key2);
      if (index1 !== -1 && index2 !== -1) {
        const minIndex = Math.min(index1, index2);
        this.currentForm.roles.splice(minIndex, 1);
      }
    },

    testAccount() {
      // console.log(this.currentForm.accountAuth)
    },
    isAllAccount(index) {
      // const userAccount = this.allUserAccount.find(item => item.userId === userId)
      const userAccount = this.allUserAccount[index]['child'];
      return userAccount.every((item) => {
        return this.currentForm.accountAuth.indexOf(item.ogAccountId) !== -1;
      });
    },
    chooseAllAccount(index) {
      const flag = this.isAllAccount(index);
      console.log(flag);
      // const userAccount = this.allUserAccount.find(item => item.userId === userId)
      const userAccount = this.allUserAccount[index]['child'];

      userAccount.forEach((item) => {
        const index = this.currentForm.accountAuth.indexOf(item.ogAccountId);
        if (flag) {
          if (index !== -1) {
            this.currentForm.accountAuth.splice(index, 1);
          }
        } else {
          if (index === -1) {
            this.currentForm.accountAuth.push(item.ogAccountId);
          }
        }
      });
    },
    // 改变角色权限
    changeRoleType() {
      // if (this.currentForm.roleType === 'finance') {
      //   this.currentForm.roles = this.rolesListFinance.map((item) => {
      //     return item.key;
      //   });
      // } else {
      //   this.currentForm.roles = [];
      // }
    },
    // 随机密码
    createPassword() {
      this.currentForm.password = generateRandomString();
    },
    getRolesStr(roles) {
      const arr = roles.map((item) => {
        // 根据权限获取对应的翻译名称
        return getRoleName(item);
      });
      return arr.join('、');
    }
  }
};
</script>

<style>
.account-checkbox .account-label {
  display: inline-block;
  max-width: 150px; /* 你可以根据需要调整这个宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style>
<style>
.admin-dialog {
  .el-tabs__item {
    height: 40px;
    line-height: 32px;
  }
}
</style>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header {
    display: flex;
    justify-content: space-between;
  }
  .content {
    padding: 20px 0 0;
  }
}
.header-select {
  margin-right: 20px;
}
.admin-dialog {
  .account-auth-content {
    display: flex;
    .user-account {
      min-width: 100px;
    }
    .account-list {
      .account-checkbox {
        width: 120px;
      }
    }
  }
}
</style>
